package org.seeplnframework.skyeye.common.alarmmerge;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import org.apache.commons.lang3.StringUtils;
import org.seeplnframework.skyeye.common.util.WeTalkUtils;
import reactor.core.publisher.Mono;
import retrofit2.Response;

import java.util.concurrent.Callable;

/**
 * @author ly
 * @date 2023/1/18
 */
@Slf4j
@AllArgsConstructor
public class PushAlarmMessageTask implements Callable<Boolean> {

    private String key;

    private String content;

    @Override
    public Boolean call() throws Exception {
        try {
            Long timestamp = System.currentTimeMillis();
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), content);
            log.info("log skyeye >>> send wechat key: {}, timestamp: {}", key, timestamp);
            Mono<Response<ResponseBody>> mono = WeTalkUtils.weTalkService.robotSendMono(key, requestBody);
            ResponseBody responseBody = mono.blockOptional().map(Response::body).orElse(null);
            String string = responseBody != null ? responseBody.string() : "";
            log.info("log skyeye >>> send wechat result: {}", string);
            if (StringUtils.isBlank(string) || string.contains("<!DOCTYPE html>")) {
                return false;
            }
            JSONObject result = JSONUtil.parseObj(string);
            if (result.get("errcode") == null || !"0".equals(String.valueOf(result.get("errcode")))) {
                return false;
            }
            return true;
        } catch (Exception e) {
            log.warn("log skyeye >>> WeTalkUtils.send occur exception", e);
            return false;
        }
    }
}
